﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MyCompanyName.AbpZeroTemplate.Web.Controllers
{
    [Abp.Web.Mvc.Authorization.AbpMvcAuthorize]
    public class SsoController : AbpZeroTemplateControllerBase
    {
        private static string SsoSalt = "SCg1hQD90mk7KmD1F6uYLQ==";

        // GET: Sso
        public ActionResult Index(string jumpUrl)
        {
            // 通过 long 的userid 取回mp要用的guid类型的userid
            Guid userId = new Guid("E757FCA6-6E36-471A-804A-A66A250A1133");
            string userName = "debug";

            string random = DateTime.Now.Ticks.ToString();
            string txt = userId.ToString() + random;
            string _cipher = EncodePassword(txt, SsoSalt);

            string comeBackUrl = jumpUrl
                .Replace("_userId=-", "&userId=" + userId.ToString() + "&")
                .Replace("userName=-", "userName=" + userName + "&")
                .Replace("random=-", "random=" + random.ToString() + "&")
                .Replace("ciphertext=-", "ciphertext=" + _cipher + "&");

            return Redirect(comeBackUrl);
        }




        private const string PasswordHashAlgorithmName = "SHA1";
        /// <summary>
        /// 将明文密码同salt一起做 SHA1 加密
        /// </summary>
        /// <param name="password">明文密码</param>
        /// <param name="salt">用户盐值</param>
        /// <returns></returns>
        public static string EncodePassword(string password, string salt)
        {
            byte[] src = Encoding.Unicode.GetBytes(password);

            byte[] saltbuf = Convert.FromBase64String(salt);

            byte[] dst = new byte[saltbuf.Length + src.Length];

            byte[] inArray = null;

            Buffer.BlockCopy(saltbuf, 0, dst, 0, saltbuf.Length);

            Buffer.BlockCopy(src, 0, dst, saltbuf.Length, src.Length);

            System.Security.Cryptography.HashAlgorithm algorithm = System.Security.Cryptography.HashAlgorithm.Create(PasswordHashAlgorithmName);
            inArray = algorithm.ComputeHash(dst);
            return Convert.ToBase64String(inArray);
        }

    }
}